/**
 * Copyright (c) 2006 RiseSoft Co.,Ltd  
 * $Header$
 */
package net.risesoft.risebi.collection.web.client;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.risesoft.risebi.collection.model.Attachment;
import net.risesoft.risebi.collection.model.Inbox;
import net.risesoft.risebi.collection.model.Outbox;
import net.risesoft.risebi.collection.model.Trashbin;
import net.risesoft.risebi.collection.model.User;
import net.risesoft.risebi.collection.model.UserSO;
import net.risesoft.risebi.collection.service.AttachmentManager;
import net.risesoft.risebi.collection.service.DynaBeanManager;
import net.risesoft.risebi.collection.service.ShortMessageManager;
import net.risesoft.risebi.collection.service.UserManager;
import net.risesoft.risebi.collection.service.UserSOManager;
import net.risesoft.risebi.collection.web.BaseAction;
import net.risesoft.risebi.commons.struts2extension.Trimable;
import net.risesoft.risebi.commons.util.ExceptionUtil;
import net.risesoft.risebi.commons.util.GUID;
import net.risesoft.risebi.commons.util.JSONUtil;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionInvocation;

/**
 *
 *
 * @author <a href="mailto: chenjian@risesoft.net">陈健</a>
 * @version $Revision$
 * 
 */
@Namespace("/client/ShortMessageAction")
public class ShortMessageAction extends BaseAction implements Trimable {

	private static final long serialVersionUID = -2983007265743619173L;
	private static Log log = LogFactory.getLog(ShortMessageAction.class);
	
	@Action(value = "listInbox", results = { @Result(name = "success", location = "/client/shortmessage/inboxList.jsp") })
	public String listInbox() throws Exception {
		return SUCCESS;
	}
	
	@Action(value = "listOutbox", results = { @Result(name = "success", location = "/client/shortmessage/outboxList.jsp") })
	public String listOutbox() throws Exception {
		return SUCCESS;
	}
	
	@Action(value = "listTrashbin", results = { @Result(name = "success", location = "/client/shortmessage/trashbinList.jsp") })
	public String listTrashbin() throws Exception {
		return SUCCESS;
	}
	
	@Action(value = "viewOutboxShortMessageDetail", results = { @Result(name = "success", location = "/client/shortmessage/viewoutboxshortmessage.jsp") })
	public String viewOutboxShortMessageDetail() throws Exception {
		outbox = (Outbox) shortMessageManager.getObject(Outbox.class, node);
		return SUCCESS;
	}
	
	@Action(value = "viewInboxShortMessageDetail", results = { @Result(name = "success", location = "/client/shortmessage/viewinboxshortmessage.jsp") })
	public String viewInboxShortMessageDetail() throws Exception {
//		修改阅读状态和阅读时间
		inbox = (Inbox) shortMessageManager.getObject(Inbox.class, node);
		inbox.setReadStatus(true);
		inbox.setReadTime(new Date());
		shortMessageManager.saveObject(inbox);
		return SUCCESS;
	}
	
	@Action(value = "prepareAdd", results = { @Result(name = "success", location = "/client/shortmessage/addshortmessage.jsp") })
	public String prepareAdd() throws Exception {
		return SUCCESS;
	}
	
	@Action(value = "prepareSelectSoItemsFromApp", results = { @Result(name = "success", location = "/client/shortmessage/selectSoItemsFromApp.jsp") })
	public String prepareSelectSoItemsFromApp() throws Exception {
		return SUCCESS;
	}
	
	@Action(value="add",
			results={@Result(name="ajax", type="ajax",params={"contentType","text/html"})}
	)
	public String add() throws Exception {
		LazyDynaBean ldb = new LazyDynaBean();
		try {
			String[] userGuidColl = receivers.split("#");
			List<User> users = userManager.getUsersByUids(userGuidColl);
			
//			组成附件列表
			List<Attachment> attachments = new ArrayList<Attachment>();
			if(upload!=null){
				for(int i=0;i<upload.length;i++){
					Attachment attachment = new Attachment();
					attachment.initAttachment(upload[i], uploadFileName[i], new GUID().toString(), Attachment.TYPE_SHORTMESSAGE);
					attachments.add(attachment);
				}
			}
			
			User user = this.getSessionUser();
			outbox.setGuid(new GUID().toString());
			outbox.setSenderGuid(user.getGuid());
			outbox.setSenderName(user.getName());
			outbox.setSendTime(new Date());
			outbox.setDeleted(false);
			outbox.setType(Outbox.TYPE_SOTOMANAGER);
			
//			获得用户的任一调查对象
			List<UserSO> userSoes = userSOManager.getUserSOByUid(user.getGuid());
			UserSO userSO = userSoes.get(0);
			String soGuid = userSO.getSo().getGuid();
			String soInstanceGuid = userSO.getSoInstanceGuid();
			outbox.setSoGuid(soGuid);
			outbox.setSoInstanceGuid(soInstanceGuid);
			Map map = dynaBeanManager.getSoInstance(soGuid, soInstanceGuid);
			outbox.setSoInstanceName(map.get("item_name").toString());
			
			shortMessageManager.sendShortMessageSoToManager(outbox, attachments, users,null);
			
			ldb.set("success", true);
			ldb.set("reason", "发送成功");
		} catch (Exception e) {
			log.error(ExceptionUtil.transformException(e));
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
		}
		this.json = JSONObject.fromObject(ldb).toString();
		return AJAX;
	}
	
	@Action(value = "refreshJson")
	public String refreshJson() throws Exception {
		try {
			User user = this.getSessionUser();
			if("jsonInboxList".equalsIgnoreCase(this.whichJson)) {
				Map<String,?> map = shortMessageManager.getInboxes(user.getGuid(), start, limit, false);
				this.json = JSONUtil.getJsonString("exclude", "outbox", map);
			}else if("jsonEmployeeList".equalsIgnoreCase(this.whichJson)) {
				Map<String,?> map = userManager.getSystemUserByEnterpriseUser(user);
				if(map==null)
					return AJAX;
				this.json = JSONUtil.getJsonString("include", "list,count,guid,departmentName,realName", map);
			}else if ("jsonOutboxList".equalsIgnoreCase(this.whichJson)) {
				Map<String,?> map = shortMessageManager.getOutboxes(user.getGuid(), start, limit, false);
				this.json = JSONUtil.getJsonString("exclude", "content", map);
			}else if ("jsonOutboxReceivers".equalsIgnoreCase(this.whichJson)) {
				Map<String,?> map = shortMessageManager.getOutboxReceivers(node, start, limit);
				this.json = JSONUtil.getJsonString("include", "list,count,guid,realName,departmentName", map);
			}else if ("jsonAttachmentsList".equalsIgnoreCase(this.whichJson)) {
				List<Attachment> list = attachmentManager.getAttachments(node, false);
				this.json = JSONUtil.getJsonString("include", "guid,name,size", list);
			}else if("jsonTrashbinList".equalsIgnoreCase(this.whichJson)) {
				Map<String,?> map = shortMessageManager.getTrashbin(user.getGuid(), start, limit);
				this.json = JSONUtil.getJsonString(null, null, map);
			}
		}catch (Exception e) {
			this.json = "[]";
			log.error(ExceptionUtil.transformException(e));
		}
		return AJAX;
	}
	
	@Action(value = "remove")
	public String remove() throws Exception {
		LazyDynaBean ldb = new LazyDynaBean();
		try {
			if(sourceType==Trashbin.SOURCETYPE_OUTBOX){
				shortMessageManager.moveToTrashBinFromOutbox(node);
			}else{
				shortMessageManager.moveToTrashBinFromInbox(node);
			}
			
			ldb.set("success", true);
		}catch (Exception e) {
			log.error(ExceptionUtil.transformException(e));
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
		}
		this.json = JSONObject.fromObject(ldb).toString();
		return AJAX;
	}
	
	@Action(value = "recover")
	public String recover() throws Exception {
		LazyDynaBean ldb = new LazyDynaBean();
		try {
			shortMessageManager.recover(node);
			
			ldb.set("success", true);
		}catch (Exception e) {
			log.error(ExceptionUtil.transformException(e));
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
		}
		this.json = JSONObject.fromObject(ldb).toString();
		return AJAX;
	}
	
	@Action(value = "clear")
	public String clear() throws Exception {
		LazyDynaBean ldb = new LazyDynaBean();
		try {
			if(node==null || node.equals("")){
				User user = this.getSessionUser();
				shortMessageManager.clearAllShortMessages(user.getGuid());
			}else{
				shortMessageManager.clearAShortMessage(node);
			}
			
			ldb.set("success", true);
		}catch (Exception e) {
			log.error(ExceptionUtil.transformException(e));
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
		}
		this.json = JSONObject.fromObject(ldb).toString();
		return AJAX;
	}

	/* (non-Javadoc)
	 * @see net.risesoft.risebi.commons.struts2extension.Trimable#afterTrim(com.opensymphony.xwork2.ActionInvocation)
	 */
	public void afterTrim(ActionInvocation invocation) {

	}

	/* (non-Javadoc)
	 * @see net.risesoft.risebi.commons.struts2extension.Trimable#preTrim(com.opensymphony.xwork2.ActionInvocation)
	 */
	public boolean preTrim(ActionInvocation invocation) {
		return true;
	}
	
	private ShortMessageManager shortMessageManager;
	private UserManager userManager;
	private UserSOManager userSOManager;
	private AttachmentManager attachmentManager;
	private DynaBeanManager dynaBeanManager;
	
	private Outbox outbox;
	private Inbox inbox;
	private File[] upload;
    private String[] uploadFileName;
    private String receivers;
    private int sourceType;
    
    public Inbox getInbox() {
		return inbox;
	}

	public void setInbox(Inbox inbox) {
		this.inbox = inbox;
	}

	public int getSourceType() {
		return sourceType;
	}

	public void setSourceType(int sourceType) {
		this.sourceType = sourceType;
	}

	public String getReceivers() {
		return receivers;
	}

	public void setReceivers(String receivers) {
		this.receivers = receivers;
	}

	public Outbox getOutbox() {
		return outbox;
	}

	public void setOutbox(Outbox outbox) {
		this.outbox = outbox;
	}

	public File[] getUpload() {
		return upload;
	}

	public void setUpload(File[] upload) {
		this.upload = upload;
	}

	public String[] getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public void setShortMessageManager(ShortMessageManager shortMessageManager) {
		this.shortMessageManager = shortMessageManager;
	}
	
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
	public void setUserSOManager(UserSOManager userSOManager) {
		this.userSOManager = userSOManager;
	}
	
	public void setAttachmentManager(AttachmentManager attachmentManager) {
		this.attachmentManager = attachmentManager;
	}
	
	public void setDynaBeanManager(DynaBeanManager dynaBeanManager) {
		this.dynaBeanManager = dynaBeanManager;
	}
}
